package com.msl.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import com.google.gson.Gson;
import com.msl.MslApp;
import com.msl.R;
import com.msl.bean.AbDcodeBean;
import com.msl.entity.CodeInfo;
import com.msl.entity.CodeInfoControl;
import com.msl.tool.ToastUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UpdateCodeService extends Service {

    private  String tag = "UpdateCodeService";
    protected OkHttpClient client ;
            String result="";
    Thread thread = null;
    protected Gson gson = null;
    MediaPlayer mediaPlayer01,mediaPlayer02;
    public UpdateCodeService() {
        gson = new Gson();
        client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build();
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        thread=new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    try {
                        if(MslApp.listcode.size()!=0)
                        {
                            String aa = MslApp.listcode.get(0);
                            String[] strs2 = aa.split(",");
                            String bb = strs2[4].replace("+","%2B");
                            String cc = "false";
                            if(strs2.length==7)
                            {
                                cc = strs2[6];
                            }
                            //如果网络不通准备写入数据库
                            ArrayList<String>  ci = new ArrayList<String>();
                            ci.add(MslApp.id2); //setBillChangeType
                            ci.add(strs2[0]); //setBillcode
                            ci.add(MslApp.sSharedPreferences.getString(MslApp.cidk,""));//setCid
                            ci.add(strs2[3]);//setCode
                            ci.add(strs2[2]);//setCodeType
                            ci.add(strs2[5]);//setManualNums
                            ci.add(strs2[1]);//setProductID
                            ci.add(MslApp.sSharedPreferences.getInt(MslApp.storeID,0)+"");//setStoreID
                            ci.add(MslApp.id1);//setStoreInfo
                            ci.add(MslApp.id1);//setStoreOtherInfo
                            ci.add(bb);//setSubBillCode
                            ci.add(MslApp.id3);//setTransactionCode
                            ci.add(MslApp.sSharedPreferences.getInt(MslApp.userID,0)+"");//setUserID

//                            Message message = new Message();
//                            message.what=3;
//                            Bundle bundle = new Bundle();
//                            bundle.putString("code",MslApp.listcode.get(0));
//                            message.setData(bundle);
//                            handler.sendMessage(message);

                            updatecode(MslApp.url+"?action=UpdateCodes_Deatil&cid="+MslApp.sSharedPreferences.getString(MslApp.cidk,"")
                                            +"&userID="+MslApp.sSharedPreferences.getInt(MslApp.userID,0)
                                            +"&storeID="+MslApp.sSharedPreferences.getInt(MslApp.storeID,0)
                                            +"&billcode="+strs2[0]
                                            +"&productID="+strs2[1]
                                            +"&codeType="+strs2[2]
                                            +"&codes="+strs2[3]
                                            +"&manualNums="+strs2[5]
                                            +"&subBillCode="+bb
                                            +"&storeInfo="+ MslApp.id1
                                            +"&storeOtherInfo="+ MslApp.id1
                                            +"&billChangeType="+MslApp.id2
                                            +"&transactionCode="+MslApp.id3
                                            +"&isQiangZhiPingTuo="+cc
                                    ,ci
                            );
                            MslApp.listcode.remove(0);
                        }
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    finally {

                    }
                }
            }
        });
        thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    void updatecode(String url,ArrayList<String> codeInfo)
    {
        final ArrayList<String> ci = codeInfo;
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            if (response.isSuccessful()) {
                AbDcodeBean ab = gson.fromJson(result, AbDcodeBean.class);
                if(ab.getErrcode()==0)
                {
                    Intent intent = new  Intent();
                    intent.setAction(MslApp.datac);
                    intent.putExtra(MslApp.codedea,ab);
                    sendBroadcast(intent);
                }
                else
                {
                    Message message = new Message();
                    message.what=0;
                    Bundle bundle = new Bundle();
                    bundle.putString("res",ab.getErrmsg());
                    message.setData(bundle);
                    handler.sendMessage(message);
                }
            }
            else
            {
                Message message = new Message();
                message.what=2;
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("ci",ci);
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Message message = new Message();
            message.what=2;
            Bundle bundle = new Bundle();
            bundle.putStringArrayList("ci",ci);
            message.setData(bundle);
            handler.sendMessage(message);
        }
    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
                    ToastUtils.showShort(getApplication(),msg.getData().getString("res"));
                    mediaPlayer01 = MediaPlayer.create(UpdateCodeService.this, R.raw.cf);
                    mediaPlayer01.start();
                    break;
                case 1:
                    ToastUtils.showSingleToast(getApplication(),"网络异常，数据上传失败");
                    List<String> ci= msg.getData().getStringArrayList("ci");
                    CodeInfo codeInfo = new CodeInfo();
                    codeInfo.setBillChangeType(ci.get(0));
                    codeInfo.setBillcode(ci.get(1));
                    codeInfo.setCid(ci.get(2));
                    codeInfo.setCode(ci.get(3));
                    codeInfo.setCodeType(ci.get(4));
                    codeInfo.setManualNums(ci.get(5));
                    codeInfo.setProductID(ci.get(6));
                    codeInfo.setStoreID(ci.get(7));
                    codeInfo.setStoreInfo(ci.get(8));
                    codeInfo.setStoreOtherInfo(ci.get(9));
                    codeInfo.setSubBillCode(ci.get(10));
                    codeInfo.setTransactionCode(ci.get(11));
                    codeInfo.setUserID(ci.get(12));
                    CodeInfoControl.insert(codeInfo);
                    break;
                case 2:
                    ToastUtils.showShort(getApplication(),"网络异常，数据上传失败");
                    mediaPlayer02 = MediaPlayer.create(UpdateCodeService.this, R.raw.herror);
                    mediaPlayer02.start();
                    List<String> cii= msg.getData().getStringArrayList("ci");
                    CodeInfo codeInfo1 = new CodeInfo();
                    codeInfo1.setBillChangeType(cii.get(0));
                    codeInfo1.setBillcode(cii.get(1));
                    codeInfo1.setCid(cii.get(2));
                    codeInfo1.setCode(cii.get(3));
                    codeInfo1.setCodeType(cii.get(4));
                    codeInfo1.setManualNums(cii.get(5));
                    codeInfo1.setProductID(cii.get(6));
                    codeInfo1.setStoreID(cii.get(7));
                    codeInfo1.setStoreInfo(cii.get(8));
                    codeInfo1.setStoreOtherInfo(cii.get(9));
                    codeInfo1.setSubBillCode(cii.get(10));
                    codeInfo1.setTransactionCode(cii.get(11));
                    codeInfo1.setUserID(cii.get(12));
                    CodeInfoControl.insert(codeInfo1);
                    break;
                case 3:
                    ToastUtils.showShort(getApplication(),msg.getData().getString("code"));
                    break;
            }
        }
    };


}
